package com.javafactroy.kunlong.codefactroy.service.base;

import cn.hutool.core.io.FileUtil;
import com.javafactroy.kunlong.base.metadata.valueobj.MetadataTable;
import com.javafactroy.kunlong.codefactroy.iface.IFileTemplate;
import com.javafactroy.kunlong.codefactroy.service.domain.valueobj.EntityProps;
import com.javafactroy.kunlong.codefactroy.service.stringtemplate.StringTemplate;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
@Accessors(chain = true)
public class FileTemplate implements IFileTemplate {

    TinFile tinFile;
    ToutFile toutFile;
    protected String clsName;
    protected String fileName;

    private StringTemplate stringTemplate;


    public FileTemplate() {

        fileName = "Mapper.template.db.mapper";
        tinFile = new TinFile().setFileName(fileName);
        toutFile = new ToutFile().setFileName(fileName);

    }

    public FileTemplate setDbTable(String dbName, String tableName) {
        toutFile.setDbName(dbName);
        toutFile.setTableName(tableName);
        return this;
    }

    public String parse(String text){
        return stringTemplate.parse(text);
    }

    public FileTemplate valueOf(MetadataTable meta) {
        clsName = meta.getClsName();
        toutFile.setTableName(meta.getTableName()).setDbName(meta.getDbName());
        return this;
    }

    public FileTemplate valueOf(EntityProps tentityProps) {
        stringTemplate = tentityProps.getStringTemplate();
        clsName = tentityProps.getClsName();
        toutFile.setTableName(tentityProps.getTableName()).setDbName(tentityProps.getDbName());
        return this;
    }

    public FileTemplate rmDbFile() {
        toutFile.rmDbFile();
        return this;
    }

    public String readFile() {
        log.info("tinFile={}", tinFile);
        return FileUtil.readUtf8String(tinFile.getFullFileName());
    }

    public void writeFile(String text) {
        log.info("toutFile={}", toutFile);
        FileUtil.writeUtf8String(text, toutFile.getOutFileName(clsName));
    }

}
